package com.neusoft.neuiotms.dcvm.service.impl;

import javax.persistence.EntityNotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcvm.converter.MockConverter;
import com.neusoft.neuiotms.dcvm.dto.MockDTO;
import com.neusoft.neuiotms.dcvm.model.Mock;
import com.neusoft.neuiotms.dcvm.repository.MockRepository;
import com.neusoft.neuiotms.dcvm.service.MockService;

@Service
public class MockServiceImpl implements MockService {

    @Autowired
    private MockRepository mockRepository;
    @Autowired
    private MockConverter mockConverter;

    @Override
    public MockDTO details(Long id) {
        Mock model;
        try {
            model = this.mockRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }
        return this.mockConverter.toDTO(model);
    }

    @Override
    public MockDTO create(MockDTO dto) {
        Mock model = this.mockRepository.findOneByApi(dto.getApi());
        if (null == model) {
            model = this.mockConverter.toModel(dto);
        } else {
            dto.setId(model.getId());
            model = this.mockConverter.toModel(dto);
        }

        this.mockRepository.save(model);
        return this.mockConverter.toDTO(model);
    }

    @Override
    public MockDTO update(Long id, MockDTO dto) {
        Mock model;
        try {
            model = this.mockRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        dto.setId(model.getId());
        model = this.mockConverter.toModel(dto);
        this.mockRepository.save(model);

        return this.mockConverter.toDTO(model);
    }

    @Override
    public void delete(Long id) {
        try {
            this.mockRepository.deleteById(id);
        } catch (final EmptyResultDataAccessException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

    }

    @Override
    public Page<MockDTO> search(Pageable pageable, Searchable searchable) {
        final Page<Mock> models = this.mockRepository.search(pageable, searchable);
        return this.mockConverter.toPageDTO(models);
    }

}
